package com.itheima.tanhua.server.interceptor;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.itheima.commons.holder.TokenHolder;
import com.itheima.commons.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

public class TokenInterceptor implements HandlerInterceptor {
 	   @Override
       public boolean preHandle(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler) throws Exception {
           String authorization = request.getHeader("Authorization");
           if (StringUtils.isEmpty(authorization)){
               throw new Exception("token不能为空");
           }
           Claims claims = JwtUtils.getClaims(authorization);
           Integer id = (Integer) claims.get("id");

           if (Objects.isNull(id)){
               throw new Exception("token已失效");
           }
           TokenHolder.set(id.toString());
           return true;
       }
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) throws Exception {
        TokenHolder.remove();
    }
}